package com.maruping.disk.login.control;

import com.maruping.disk.mybatis.entity.PtUserEntity;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import javax.imageio.ImageIO;

@Controller
@RequestMapping("/login")
public class LoginControl {


@Resource
private HttpSession httpSession;

    @RequestMapping("/login")
    public String loginPage(@RequestParam(value = "error", required = false) String error) {
        httpSession.setAttribute("lang", LocaleContextHolder.getLocale().toString());

        if (error != null) {
            Integer errorCount = (Integer) httpSession.getAttribute("loginErrorCount");
            httpSession.setAttribute("loginErrorCount", errorCount == null ? 1 : errorCount + 1);
        } else {
            httpSession.removeAttribute("loginErrorCount");
        }
        return "login/loginPage";
    }
    @RequestMapping("/register") // 完整路由：/login/register
    public String registerPage() {
        // 返回注册页视图（路径：templates/login/registerPage.html）
        return "login/registerPage";
    }


    @RequestMapping("/main")
    public String mainPage() {
        return "redirect:/";
    }

    /**
     * 生成验证码图片（完全动态生成，不依赖任何外部图片文件）
     */
    @RequestMapping("/getCaptcha")
    public void getCaptcha(HttpServletResponse response, HttpSession session) throws IOException {
        // 1. 生成4位随机验证码
        String code = generateRandomCode();
        session.setAttribute("sessionCaptcha", code);

        // 2. 创建图片缓冲区
        BufferedImage image = new BufferedImage(120, 40, BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();

        try {
            // 绘制背景（替代captcha_bg.png的作用）
            g.setColor(new Color(240, 240, 240)); // 浅灰色背景
            g.fillRect(0, 0, 120, 40);

            // 绘制边框
            g.setColor(Color.LIGHT_GRAY);
            g.drawRect(0, 0, 119, 39); // 1像素边框

            // 设置字体
            g.setFont(new Font("Arial", Font.BOLD | Font.ITALIC, 22));

            // 绘制验证码文本（随机颜色）
            for (int i = 0; i < code.length(); i++) {
                // 随机颜色，增强安全性
                g.setColor(new Color(
                        (int)(Math.random() * 100),  // 红色分量（0-100，避免过亮）
                        (int)(Math.random() * 100),  // 绿色分量
                        (int)(Math.random() * 100)   // 蓝色分量
                ));
                // 随机Y轴位置，增加识别难度
                int yPos = 25 + (int)(Math.random() * 6) - 3;
                g.drawString(String.valueOf(code.charAt(i)), 20 + i * 20, yPos);
            }

            // 绘制干扰线（增强安全性）
            g.setColor(new Color(200, 200, 200)); // 灰色干扰线
            for (int i = 0; i < 4; i++) {
                g.drawLine(
                        (int)(Math.random() * 120),
                        (int)(Math.random() * 40),
                        (int)(Math.random() * 120),
                        (int)(Math.random() * 40)
                );
            }

            // 绘制干扰点
            for (int i = 0; i < 30; i++) {
                g.fillRect(
                        (int)(Math.random() * 120),
                        (int)(Math.random() * 40),
                        1, 1
                );
            }

            // 3. 输出图片到响应流
            response.setContentType("image/png");
            response.setHeader("Pragma", "no-cache"); // 禁止缓存
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);

            try (OutputStream os = response.getOutputStream()) {
                ImageIO.write(image, "png", os);
                os.flush();
            }
        } finally {
            g.dispose(); // 释放图形资源
        }
    }

    // 生成随机验证码
    private String generateRandomCode() {
        String chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        StringBuilder code = new StringBuilder();
        for (int i = 0; i < 4; i++) {
            code.append(chars.charAt((int) (Math.random() * chars.length())));
        }
        return code.toString();
    }
    @RequestMapping("/forgotPassword")
    public String forgotPassword() {
        return "login/forgotPassword";
    }


}
